<template>
  <el-row>
    <div class="block">
      <el-date-picker v-model="value2" type="datetimerange" range-separator="To" start-placeholder="起始日期" end-placeholder="结束日期" />
    </div>
  </el-row>
  <div>
    <el-card><div ref="chart2" style="height: 400px; width: 1300px"></div></el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from "vue";
import * as echarts from "echarts";
import axios from "axios";

const value2 = ref([]);
const chart = ref();
const chart2 = ref();

// 定义所有区域及其对应的URL参数
const areas = [
  { value: "BB7CAH012490", label: "装配" },
  { value: "BB3CBK01230", label: "缸体M1" },
  { value: "BB4CBK02230", label: "缸体M2" },
  { value: "BB1CHD01190", label: "缸盖M1" },
  { value: "BB2CHD02190", label: "缸盖M2" },
  { value: "BB5CCK01150B", label: "曲轴" }
];

function formatDate(d: string) {
  const date = new Date(d);
  const YY = date.getFullYear() + "-";
  const MM = (date.getMonth() + 1).toString().padStart(2, '0') + "-";
  const DD = date.getDate().toString().padStart(2, '0');
  const hh = date.getHours().toString().padStart(2, '0') + ":";
  const mm = date.getMinutes().toString().padStart(2, '0') + ":";
  const ss = date.getSeconds().toString().padStart(2, '0');
  return `${YY}${MM}${DD} ${hh}${mm}${ss}`;
}

const use_show_data_in_html3 = async () => {
  try {
    let allProductionEnergy = [];
    let allNonProductionEnergy = [];
    let allHourtarget = [];
    let allHourtarget2 = [];

    for (let area of areas) {
      const start_time = formatDate(value2.value[0]);
      const end_time = formatDate(value2.value[1]);
      let end_time_for_yyyymmdd = new Date(end_time);
      end_time_for_yyyymmdd.setDate(end_time_for_yyyymmdd.getDate() - 1);
      const start_timeYYYYMMDD = start_time.split(' ')[0];
      const end_timeYYYYMMDD = formatDate(end_time_for_yyyymmdd).split(' ')[0];
      const truncatedValue3 = area.value.slice(0, 3);
      const productValue3 = area.value.slice(3, 8);
      const extraValue3 = area.value.slice(8, 12);

      const construct_url = `http://10.64.35.32:8000/energy_analysis/get_energy_data/?start_time=${start_time}&end_time=${end_time}&item=${truncatedValue3}&page_size=100001`;
      const product_url = `http://10.64.35.32:8000/man_ana_sql_server/get_GdHistory_data/?start_time=${start_timeYYYYMMDD}&end_time=${end_timeYYYYMMDD}&sub_area=${productValue3}&equipment_id=${extraValue3}&page_size=100001`;
      const target2_url = `http://10.64.35.32:8000/manufacture_analysis/get_ms_cycle_data/?&station=${truncatedValue3}&page_size=1&page=2`;
      console.log(product_url)
      const response = await axios.get(construct_url);
      const energyData = response.data;
      const response1 = await axios.get(product_url);
      const productionData = response1.data;
      const response3 = await axios.get(target2_url);

      const hourtarget = parseFloat(response3.data[0]?.equipment_target_time?.toFixed(2) || '0.00');
      const hourtarget2 = parseFloat(response3.data[0]?.push_pull_target_time?.toFixed(2) || '0.00');

      const productionDataMap = productionData.reduce((acc, curr) => {
        const date = new Date(curr.production_date).toISOString().split('T')[0];
        if (!acc[date]) {
          acc[date] = 0;
        }
        acc[date] += curr.sum || 0;
        return acc;
      }, {});

      const totalProduction = productionData.reduce((acc, curr) => acc + (curr.sum || 0), 0);

      let groupedData = groupByDefault(energyData, productionDataMap);

      let productionEnergy = 0;
      let nonProductionEnergy = 0;

      Object.values(groupedData).forEach(records => {
        records.sort((a, b) => new Date(a.time) - new Date(b.time));
        let prevVal = null;
        let productionTotal = 0;
        let nonProductionTotal = 0;
        let productionHourCount = 0;
        let nonProductionHourCount = 0;

        records.forEach(record => {
          if (prevVal !== null) {
            const diff = parseInt(record.val, 10) - prevVal;
            if (area.value === 'BB5CCK01150B') { 
              if (diff > 100 && diff < 1000) {
                productionTotal += diff;
                productionHourCount++;
              } else if (diff >= 0 && diff <= 100) {
                nonProductionTotal += diff;
                nonProductionHourCount++;
              }
            } else if (area.value === 'BB7CAH012490') { 
              if (diff > 21 && diff < 1000) {
                productionTotal += diff;
                productionHourCount++;
              } else if (diff >= 0 && diff <= 21) {
                nonProductionTotal += diff;
                nonProductionHourCount++;
              }
            } else { 
              if (diff > 60 && diff < 1000) {
                productionTotal += diff;
                productionHourCount++;
              } else if (diff >= 0 && diff <= 60) {
                nonProductionTotal += diff;
                nonProductionHourCount++;
              }
            }
          }
          prevVal = parseInt(record.val, 10);
        });
        console.log('productionTotal',productionTotal)
        productionEnergy += (productionHourCount ? (productionTotal / productionHourCount).toFixed(2) : '0.00');
        nonProductionEnergy += (nonProductionHourCount ? (nonProductionTotal / nonProductionHourCount).toFixed(2) : '0.00');
        console.log('productionEnergy',productionEnergy)
        console.log('nonProductionEnergy',nonProductionEnergy)
        console.log('productionHourCount',productionHourCount)
        console.log('nonProductionHourCount',nonProductionHourCount)
      });

      allProductionEnergy.push(parseFloat(productionEnergy));
      allNonProductionEnergy.push(parseFloat(nonProductionEnergy));
      allHourtarget.push(hourtarget);
      allHourtarget2.push(hourtarget2);
    }

    initChart2(
      allProductionEnergy,
      allNonProductionEnergy,
      allHourtarget,
      allHourtarget2,
      areas.map(area => area.label)
    );
  } catch (error) {
    console.error("Error fetching data:", error);
  }
};

function groupByDefault(data: any[], productionDataMap: any) {
  return data.reduce((acc, curr) => {
    if (!acc['总计']) {
      acc['总计'] = [];
    }
    acc['总计'].push(curr);
    return acc;
  }, {});
}

let initChart2 = async (
  prodEnergyData,
  nonProdEnergyData,
  hourtarget,
  hourtarget2,
  categories
) => {
  if (chart2.value == null) {
    return;
  }

  echarts.dispose(chart2.value);
  var myChart2 = echarts.init(chart2.value);

  let option = {
    title: {
      text: `各线能耗`,
      left: "left",
      textStyle: {
        color: "black", 
      },
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['生产小时能耗', '非生产小时能耗', '生产小时能耗指标','非生产小时能耗指标'],
      orient: "horizontal",
      left: "right",
      top: "top",
      itemGap: 10,
    },
    xAxis: {
      type: 'category',
      data: categories,
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '生产小时能耗',
        position: 'left',
        offset: 20,
      },
      {
        type: 'value',
        name: '非生产小时能耗',
        position: 'right',
        offset: 20,
      }
    ],
    series: [
      {
        name: "生产小时能耗",
        type: "bar",
        data: prodEnergyData,
        yAxisIndex: 0,
        color: '#2ec7c9',
        label: {
          show: true, 
          position: 'top',  
        },
      },
      {
        name: "非生产小时能耗",
        type: "bar",
        data: nonProdEnergyData,
        yAxisIndex: 1,
        color: '#b6a2de',
        label: {
          show: true, 
          position: 'top',  
        },
      },
      {
        name: "生产小时能耗指标",
        type: "line",
        data: hourtarget,
        yAxisIndex: 0,
        color: '#516b91',
      },
      {
        name: "非生产小时能耗指标",
        type: "line",
        data: hourtarget2,
        yAxisIndex: 1,
        color: '#59c4e6',
      },
    ]
  };

  myChart2.setOption(option);
};

onMounted(() => {
    const today = new Date();
    const ago = new Date(today);
    ago.setDate(ago.getDate() - 1);
    ago.setHours(8, 0, 0, 0); 
    let tomorrow = new Date(today);
    tomorrow.setDate(tomorrow.getDate());
    tomorrow.setHours(8, 0, 0, 0);

    value2.value = [ago, tomorrow];
    use_show_data_in_html3();
});

watch(value2, async (newVal, oldVal) => {
  if (newVal && newVal.length === 2) {
    await use_show_data_in_html3();
  }
});
</script>

<style scoped>

</style>